# -*- coding: utf-8 -*-
import StringIO

__author__ = 'ggcall'

import requests
import sqlite3
import re
import os
from PIL import Image

def randcode(pic):
    # pic_name="old.jpg"
    # f = open(pic_name, 'wb')
    # f.write(pic)
    # f.close
    # time.sleep(5)
    # box=(0,0,60,20)
    im=StringIO.StringIO(pic)
    # im.save(pic_name)
    im=Image.open(im)
    # im=im.crop(box)
    # im=im.filter(ImageFilter.MedianFilter())
    # enhancer = ImageEnhance.Contrast(im)
    # im = enhancer.enhance(1)
    # im = im.convert('L')
    # im.show()
    im.save("code.jpg")

    os.popen('tesseract.exe code.jpg code digits')
    with open('code.txt') as file:
        t=file.read()
    print 'txt:',t
    t=re.findall('\d',t)
    if(len(t)==4):
        return ''.join(t)
    else:
        return ''

pic_url ='http://www.npedi.com/edi/ediweb/image.jsp'
login_url='http://www.npedi.com/edi/webLoginAction.do'
post_data=dict()
post_data['usercode']='GUEST'
post_data['password']='guest'
post_data['randcode']=''
login_pattern='<font color="#FF3300" >GUEST</font>'

# 登录的地址
def getpic(url):

    r=requests.get(url)
    code=randcode(r.content)
    return code,r.cookies

def checkpic(url,code):
    while not re.match('\d{4}',code):
        print 'pic check fail'
        code,cookies=getpic(url)
        # code='1'
    print 'pic check ok'
    return code,cookies


def gethtml(url,params,cookies):
    # post_data['randcode']=''
    login_html=requests.get(url,params=params,cookies=cookies).text
    return login_html

def checkhtml(url,params,cookies,html):
    while not re.search(login_pattern,html):
        print 'login fail'
        html=gethtml(url,params,cookies)
        # html=''
    print 'success'
    return True

html=''
post_data['randcode'],cookies=checkpic(pic_url,post_data['randcode'])
checkhtml(login_url,post_data,cookies,html)
dbpath=os.path.join(os.path.dirname(__file__),os.path.pardir,'ctms.db3')
print dbpath
con=sqlite3.connect(dbpath)
cur=con.execute('select * from t_ct')
rv = [dict((cur.description[idx][0], value) for idx, value in enumerate(row)) for row in cur.fetchall()]
# cookie=requests.get('http://122.227.172.219:50004/get_npedi_auth').json()['cookie']
cookie=cookies['JSESSIONID']
print cookie
url='http://www.npedi.com/edi/voyageInfoAction.do'
cookies=dict(JSESSIONID=cookie)
rv=[{'ct_code':'BLCT'}]
for r in rv:
    print r['ct_code']
    for i in range(1,2):
        print i,r['ct_code']
        params={'pageIndex':i,'ename':'','voyage':'','cpcode':r['ct_code']}
        res=requests.get(url,params=params,cookies=cookies).text
        print res
